package com.roger.ats.init;

import android.content.ContentValues;
import android.graphics.Point;
import android.net.Uri;
import android.os.Environment;
import android.os.RemoteException;
import android.os.SystemClock;
import android.provider.CalendarContract;
import android.provider.CallLog;
import android.support.test.InstrumentationRegistry;
import android.util.Log;

import com.roger.ats.init.cases.AccountInit;
import com.roger.ats.init.cases.SettingsInit;
import com.roger.ats.init.util.CfgUtils;
import com.roger.ats.init.util.LogUtils;
import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.UiWatch;
import com.roger.uia.helper.manager.Package;
import com.roger.uia.helper.manager.Telephony;
import com.roger.uia.helper.util.ContentUtils;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.StrUtils;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;

import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.waitTime;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MainSys {
    private static final String TAG = "Test" + MainSys.class.getSimpleName();
    private static LogUtils logUtils = new LogUtils();
    private static CfgUtils cfgUtils = new CfgUtils();

    @BeforeClass
    public static void beforeClass() throws Throwable{
        Package.pac().grantAllPerms(InstrumentationRegistry.getTargetContext().getPackageName());
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
    }

    @Before
    public void setUp() {
        Log.d(TAG, "-- set up --");
        UiWatch.getWatcher().runErrorWatcher();
        UiWatch.getWatcher().runSpecialWatcher();
    }

    @After
    public void tearDown() {
        Log.d(TAG, "-- tear down --");
        UiWatch.getWatcher().removeErrorWatcher();
        UiWatch.getWatcher().removeSpecialWatcher();
    }

    @AfterClass
    public static void afterClass() throws Throwable{
        //mDevice.executeShellCommand("reboot");
    }

    @Test
    public void Test(){
//        Case000_initLogs();
//        SettingsInit.connWifi();
//        if(Package.pac().isAppInstalled("com.android.email")){
//            Package.pac().grantAllPerms("com.android.email");
//            AccountInit.launchPOP3();
//            AccountInit.launchIMAP();
//        }
        String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ScreenState/ori.txt";
        String FILE_PATH2 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ScreenState/switch.txt";
        String isOn="1";
        if(new File(FILE_PATH2).exists()) isOn=FileUtils.readTxtS(FILE_PATH2);
        while (isOn.equals("1")){
            String s = FileUtils.readTxtS(FILE_PATH);
            Log.d("test1",s);
            if(s.equals("1") && mDevice.isNaturalOrientation()){
                try {
                    mDevice.setOrientationLeft();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }else if(s.equals("0") && ! mDevice.isNaturalOrientation()){
                try {
                    mDevice.setOrientationNatural();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            SystemClock.sleep(waitTime * 3);
            if(new File(FILE_PATH2).exists()) isOn=FileUtils.readTxtS(FILE_PATH2);
        }

    }

    @Test
    public void Case000_initLogs(){
        FileUtils.deleteFile(UiBase.filePath + "ATS/logs/AtsLogs.txt");
        logUtils.printLog("[version]= V1.1.0_20200305");
        try {
            logUtils.printLog("[model name]=" + UiBase.mDevice.executeShellCommand("getprop ro.product.model").replace("\n",""));
            logUtils.printLog("[serial no]=" + UiBase.mDevice.executeShellCommand("getprop ro.serialno").replace("\n",""));
            logUtils.printLog("[build info]=" + UiBase.mDevice.executeShellCommand("getprop ro.build.description").replace("\n",""));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void Case001_intoHomeScreen(){
        for(int i=0;i<5;i++){
            if(UiBase.existObj(UiBase.objSelect[2],"(?i)已连接到 USB 调试|USB debugging connected")) {
                mDevice.swipe(StrUtils.SCREEN_W/2,StrUtils.SCREEN_H-20,StrUtils.SCREEN_W/2,20,50);
                SystemClock.sleep(waitTime/5);
                mDevice.pressHome();
            }else{
                break;
            }
        }
    }

    @Test
    public void Case002_changeWallpaper(){
        mDevice.pressHome();
        String[] pic= cfgUtils.getCfg("paper=").split("/");
        if(!pic[0].equals("null")){
            logUtils.printLog("==start set wallpaper==");
            try {
                UiBase.openApp(StrUtils.settingPac);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingDashBoard,10);
                UiBase.scrollReidClickObj(StrUtils.settingDashBoard,UiBase.objSelect[2],StrUtils.settingDisplay);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingList,3);
                UiBase.scrollReidClickObj(StrUtils.settingList,UiBase.objSelect[2],"Wallpaper|壁纸");
                UiBase.waitObj(UiBase.objSelect[2],"Choose wallpaper from|选择壁纸来源",3);
                UiBase.scrollReidClickObj(StrUtils.settingList,UiBase.objSelect[2],"Wallpapers|壁纸");
                UiBase.waitClickObj(UiBase.objSelect[2],"My photos|我的照片",3);
                UiBase.waitClickObj(UiBase.objSelect[6],"Show roots|显示根目录",3);
                UiBase.waitClickObj(UiBase.objSelect[2],"Images|图片",3);
                for (String aPic : pic) UiBase.waitClickObj(UiBase.objSelect[2], aPic, 5);
                UiBase.waitClickObj(UiBase.objSelect[2],"Set wallpaper|设置壁纸",5);
                UiBase.waitClickObj(UiBase.objSelect[2],"Home screen|主屏幕",5);
                UiBase.waitObjCheck(UiBase.objSelect[3],StrUtils.settingList,5);
                logUtils.printLog("set wallpaper success");
            } catch (Throwable e) {
                logUtils.printLog("set wallpaper fail");
            }finally {
                mDevice.pressHome();
            }
        }
    }

    @Test
    public void Case003_changeFont(){
        mDevice.pressHome();
        String font= cfgUtils.getCfg("size=");
        if(!font.equals("null")){
            logUtils.printLog("==start set font size==");
            try {
                UiBase.openApp(StrUtils.settingPac);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingDashBoard,10);
                UiBase.scrollReidClickObj(StrUtils.settingDashBoard,UiBase.objSelect[2],StrUtils.settingDisplay);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingList,3);
                UiBase.scrollReidClickObj(StrUtils.settingList,UiBase.objSelect[2],"Font size|字体大小");
                UiBase.waitClickObj(UiBase.objSelect[6],font,3);
                UiBase.checkPoint("check status",UiBase.objChecked(UiBase.objSelect[6],font));
                logUtils.printLog("set font size success");
            } catch (Throwable e) {
                logUtils.printLog("set font size fail");
            }finally {
                mDevice.pressHome();
            }
        }
    }

    @Test
    public void Case004_setMultiUser(){
        mDevice.pressHome();
        String arg = cfgUtils.getCfg("user=");
        if(!arg.equals("null")){
            logUtils.printLog("==start set multi user==");
            try {
                UiBase.openApp(StrUtils.settingPac);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingDashBoard,10);
                UiBase.scrollReidClickObj(StrUtils.settingDashBoard,UiBase.objSelect[2],"Users & accounts|用户和帐号");
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingList,3);
                UiBase.scrollReidClickObj(StrUtils.settingList,UiBase.objSelect[2],"Multiple users|多用户");
                if(!UiBase.existObj(UiBase.objSelect[0],arg)){
                    UiBase.waitClickObj(UiBase.objSelect[2],"(?i)ADD USER|添加用户",3);
                    UiBase.waitClickObj(UiBase.objSelect[2],"Standard user|一般用户",3);
                    UiBase.waitClickObj(UiBase.objSelect[2],"(?i)CONTINUE|继续",3);
                    UiBase.waitObj(UiBase.objSelect[2],"Name|姓名",3);
                    UiBase.inputTxtToObj(UiBase.objSelect[2],"Name|姓名",arg);
                    UiBase.waitClickObj(UiBase.objSelect[2],"(?i)NEXT|下一步",3);
                    UiBase.waitClickObj(UiBase.objSelect[2],"(?i)CLOSE|关闭",20);
                }
                UiBase.checkPoint("check status",UiBase.existObj(UiBase.objSelect[0],arg));
                logUtils.printLog("set multi user success : " + arg);
            } catch (Throwable e) {
                logUtils.printLog("set multi user fail : " + arg);
            }finally {
                mDevice.pressHome();
            }
        }
    }

    @Test
    public void Case005_addContacts() {
        mDevice.pressHome();
        String arg = cfgUtils.getCfg("contact=");
        if(arg.equals("true")){
            logUtils.printLog("==start add contacts==");
            try {
                UiBase.forceStopApp("com.android.contacts");
                UiBase.openApp("com.android.contacts");
                UiBase.waitClickObj(UiBase.objSelect[6],"Open navigation drawer|打开抽屉式导航栏",10);
                UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.settings,3);
                UiBase.waitClickObj(UiBase.objSelect[2],"Import|导入",3);
                UiBase.waitClickIfObjExist(UiBase.objSelect[2],StrUtils.allow,5);
                UiBase.waitClickObj(UiBase.objSelect[2],"Internal shared storage|内部共享存储空间",3);
                UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.next,3);
                UiBase.waitClickObj(UiBase.objSelect[2],"Tablet|平板电脑",3);
                UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.next,3);
                SystemClock.sleep(waitTime * 10);
                UiBase.checkPoint("check status",ContentUtils.content().existContact());
                logUtils.printLog("add contacts success");
            } catch (Throwable e) {
                logUtils.printLog("add contacts fail" );
            }finally {
                mDevice.pressHome();
            }
        }

    }

    @Test
    public void Case006_connectWifi(){
        SettingsInit.connWifi();
    }

    @Test
    public void Case007_addAccount(){
        if(Package.pac().isAppInstalled("com.android.email")){
            Package.pac().grantAllPerms("com.android.email");
            AccountInit.launchPOP3();
            AccountInit.launchIMAP();
        }
        AccountInit.launchLENOVO();
    }

    @Test
    public void Case008_setLock(){
        mDevice.pressHome();
        String arg = cfgUtils.getCfg("lock=");
        if(!arg.equals("null")){
            String pin = cfgUtils.getCfg("pin=");
            String pwd = cfgUtils.getCfg("pwd=");
            logUtils.printLog("==start set screen lock==");
            try {
                UiBase.openApp(StrUtils.settingPac);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingDashBoard,10);
                UiBase.scrollReidClickObj(StrUtils.settingDashBoard,UiBase.objSelect[2],StrUtils.settingSecurity);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingList,3);
                UiBase.scrollReidClickObj(StrUtils.settingList,UiBase.objSelect[2],StrUtils.ScreenLock);
                UiBase.waitClickObj(UiBase.objSelect[2],arg,3);
                if(arg.contains("Pattern")){
                    UiBase.waitClickObj(UiBase.objSelect[2],"NO|否",3);
                    swipePattern();
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.next,3);
                    swipePattern();
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.ok,3);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.done,5);
                }else if(arg.contains("PIN")){
                    UiBase.waitClickObj(UiBase.objSelect[2],"NO|否",3);
                    UiBase.waitObjCheck(UiBase.objSelect[3],"com.android.settings:id/password_entry",3);
                    UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password_entry",pin);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.next,3);
                    UiBase.waitObjCheck(UiBase.objSelect[3],"com.android.settings:id/password_entry",3);
                    UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password_entry",pin);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.ok,3);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.done,5);
                }else if(arg.contains("Password")){
                    UiBase.waitClickObj(UiBase.objSelect[2],"NO|否",3);
                    UiBase.waitObjCheck(UiBase.objSelect[3],"com.android.settings:id/password_entry",3);
                    UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password_entry",pwd);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.next,3);
                    UiBase.waitObjCheck(UiBase.objSelect[3],"com.android.settings:id/password_entry",3);
                    UiBase.inputTxtToObj(UiBase.objSelect[3],"com.android.settings:id/password_entry",pwd);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.ok,3);
                    UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.done,5);
                }
                UiBase.checkPoint("check status",UiBase.existObj(UiBase.objSelect[2],arg));
                logUtils.printLog("set screen lock success : " + arg);
            } catch (Throwable e) {
                logUtils.printLog("set screen lock fail : " + arg);
            }finally {
                mDevice.pressHome();
            }
        }
    }

    private void swipePattern(){
        ArrayList<Point> p = new ArrayList<>();
        String[] pat = cfgUtils.getCfg("pattern=").split(";");
        for (String aPat : pat) {
            int x = Integer.parseInt(aPat.split(",")[0]);
            int y = Integer.parseInt(aPat.split(",")[1]);
            Point p0 = new Point();
            p0.x = x;
            p0.y = y;
            p.add(p0);
        }
        for(int i=0;i<p.size();i++){
            Log.d(TAG, String.valueOf(p.get(i)));
        }
        Point[] points = new Point[p.size()];
        p.toArray(points);
        mDevice.swipe(points,40);
    }

    @Test
    public void noLock(){
        mDevice.pressHome();
        try {
            UiBase.openApp(StrUtils.settingPac);
            UiBase.waitObj(UiBase.objSelect[3], StrUtils.settingDashBoard, 10);
            UiBase.scrollReidClickObj(StrUtils.settingDashBoard, UiBase.objSelect[2], StrUtils.settingSecurity);
            UiBase.waitObj(UiBase.objSelect[3], StrUtils.settingList, 3);
            UiBase.scrollReidClickObj(StrUtils.settingList, UiBase.objSelect[2], StrUtils.ScreenLock);
            UiBase.waitClickObj(UiBase.objSelect[2], StrUtils.lockNone, 3);
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            mDevice.pressHome();
        }
    }

    private void addContact(){
        logUtils.printLog("==start add contacts==");
        String add = cfgUtils.getCfg("contact=");
        if(add.equals("true")){
            ContentUtils.content().delAllContact();
            String count = cfgUtils.getCfg("contact_counts=");
            StringBuilder name = new StringBuilder("Test");
            StringBuilder num = new StringBuilder("13");
            for(int i=0;i<Integer.parseInt(count);i++){
                name.append(i);
                for(int j=0;j<9;j++){
                    num.append(new Random().nextInt(10));
                }
                ContentUtils.content().addContact(name.toString(),num.toString(),name.toString()+"@lenovo.com","北京市朝阳区，门牌号:"+ i);
                name = new StringBuilder("Test");
                num = new StringBuilder("13");
            }
            logUtils.printLog("add contacts success");
        }else{
            logUtils.printLog("skip add contacts");
        }
    }

    private void addCalendar(){
        logUtils.printLog("==start add calendar activities==");
        String add = cfgUtils.getCfg("calendar=");
        if(add.equals("true")){
            String count = cfgUtils.getCfg("activity_counts=");
            long  time = System.currentTimeMillis();
            for(int i=0;i<Integer.parseInt(count);i++){
                time -= 86400000L;
                Log.d(TAG, String.valueOf(time));
                ContentValues values = new ContentValues();
                values.put(CalendarContract.Events.DTSTART, time);
                values.put(CalendarContract.Events.DTEND,time);
                values.put(CalendarContract.Events.TITLE, "Test"+i);
                values.put(CalendarContract.Events.CALENDAR_ID, 1);
                values.put(CalendarContract.Events.ALL_DAY, 1);
                values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
                InstrumentationRegistry.getTargetContext().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, values);
                values.clear();
            }
            logUtils.printLog("add calendar activities success");
        }else{
            logUtils.printLog("skip add calendar activities");
        }
    }

}
